package com.ajl.wx.utils;

import ch.qos.logback.classic.sift.AppenderFactoryUsingJoran;
import com.ajl.wx.config.WebApplicationProperties;
import org.apache.commons.io.IOUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Random;

public class FileUtil {
    /**
     * 获取文件类型
     * @param joinSpot 是否前缀加.
     * @param contentType
     * @return
     */
    public static String getFileExtendNameForContentType(boolean joinSpot ,String contentType){
        String type =contentType.substring(contentType.indexOf("/")+1);
        return joinSpot?"."+type:type;
    }
    public static String getFileExtendNameForContentType(boolean joinSpot,MultipartFile multipartFile){
        return getFileExtendNameForContentType(joinSpot,multipartFile.getContentType());
    }

    /**
     * md5获取，格式System.currentTimeMillis()+fileName+random(100)
     * @param fileName
     * @return
     */
    public static String generateFileMd5(String fileName){
        String temp =String.join(",",
                System.currentTimeMillis()+"",
                fileName,
                new Random().nextInt(100)+"");
        return DigestUtils.md5DigestAsHex(temp.getBytes());
    }

    /**
     * 生成文件对象，如果父文件不存在则创建
     * @param parent
     * @param name
     * @return
     */
    public static File generateFile(String parent,String name){
        File file = new File(parent, name);
        if (Files.notExists(Paths.get(file.getParent()))){
            try {
                Files.createDirectories(Paths.get(file.getParent()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  new File(parent,name);
    }
}
